from tkinter import *
import tkinter.ttk as ttk
import json
import pyperclip
import lzstring
import webbrowser
class Window:
    root = Tk() 
    version= '1.1.0'
    language= 'zh-CN' 
    resource_open= IntVar()
    senior=IntVar()
    senior_open=IntVar()
    prestige=IntVar()
    prestige_open=IntVar()
    double_speed=IntVar()
    arpa_sequence=IntVar()
    foreign_open=IntVar()
    foreign_value=StringVar() 
    dkills_open=IntVar() 
    ships_name_open=IntVar()
    strings = {} 

    def __init__(self):
        self.init_config()
        strings = self.read_json_file('./language/' + self.language + '.json')
        self.strings = strings
        root = self.root
        root.resizable(False, False) 
        root.title(strings['title'] + " " + self.version) 

        self.draw_menu()
        self.draw(strings['resource'], self.resource_open) 
        self.draw_int_text(strings['senior'], self.senior_open, self.senior) 
        self.draw_int_text(strings['prestige'], self.prestige_open, self.prestige) 
        self.draw(strings['double_speed'], self.double_speed) 
        self.draw(strings['arpa_sequence'], self.arpa_sequence) 
        self.draw_combobox(strings['foreign'], self.foreign_open, self.foreign_value,[strings['anx'],strings['occ'],strings['buy']]) 
        self.draw(strings['dkills'], self.dkills_open) 
        self.draw(strings['ships_name'], self.ships_name_open)  
        Button(root, text="执行", command=self.execute_command).pack(side=BOTTOM, padx=10, pady=10, fill=X, expand=True)   
        
    
    def execute_command(self):     
        clipboard_content = pyperclip.paste().strip()
        lz = lzstring.LZString()
        decoded_bytes = lz.decompressFromBase64(clipboard_content)
        obj =json.loads(decoded_bytes)
        self.update_obj(obj)
        r = lz.compressToBase64(json.dumps(obj))
        pyperclip.copy(r)
    
    def draw_menu(self):
        root = self.root
        # 创建菜单栏
        menubar = Menu(root)
        
        # 创建菜单项
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Game", command=lambda: webbrowser.open("https://pmotschmann.github.io/Evolve/"))
        filemenu.add_command(label="Wiki", command=lambda: webbrowser.open("https://pmotschmann.github.io/Evolve/wiki.html"))
        filemenu.add_command(label="Strategy", command=lambda: webbrowser.open("https://docs.qq.com/sheet/DSGZueEtwcHdZclNT?u=344329ebf4b84eefa6cc924acc148442&tab=abaqz7"))
        filemenu.add_command(label="Github", command=lambda: webbrowser.open("https://github.com/pmotschmann/Evolve"))
        filemenu.add_command(label="Instructions", command=lambda: webbrowser.open("https://gitee.com/AbaiDev/evolve-mod-tool"))
        
        # 将菜单项添加到菜单栏
        menubar.add_cascade(label="Help", menu=filemenu)
        
        # 将菜单栏添加到根窗口
        root.config(menu=menubar)

    def update_obj(self, obj):
        resource =  obj['resource']
        prestige =  obj['prestige']
        if self.resource_open.get() == 1:
            for key in resource:
                r = resource[key]
                if r['display']:
                    r['amount'] = r['max']
        if self.senior_open.get() == 1:
            for key in resource:
                r = resource[key]
                if r['max'] < 0:
                    r['amount'] = int(self.senior.get())
        if self.prestige_open.get() == 1:
            for key in prestige:
                prestige[key]['count'] = int(self.prestige.get())
        if self.foreign_open.get() == 1:
            foreign = obj['civic']['foreign']
            for key in foreign:
                if self.foreign_value.get() == self.strings['anx']:
                    foreign[key]['anx'] = TRUE
                elif self.foreign_value.get() == self.strings['occ']:
                    foreign[key]['occ'] = TRUE
                elif self.foreign_value.get() == self.strings['buy']:
                    foreign[key]['buy'] = TRUE
        if self.dkills_open.get() == 1:
            if obj['portal']['observe']:
                obj['portal']['observe']['stats']['total']['kills']['drones']=999999
                obj['portal']['observe']['stats']['period']['kills']['drones']=999999
                obj['stats']['dkills']=999999
        if self.ships_name_open.get() == 1:
            shipyard = obj['space']['shipyard']
            if shipyard:
                ships = shipyard['ships']
                if ships:
                    for item in ships:
                        if item['transit'] > 0:
                            item['transit'] = 1
        if self.double_speed.get() == 1:
            obj['stats']['current'] = 1716000000000
        if self.arpa_sequence.get() == 1:
            obj['arpa']['sequence']['time'] = 1

    def init_config(self): 
        self.senior.set(10000000000000000)
        self.prestige.set(10000000000000000) 
        self.double_speed.set(1)
        self.resource_open.set(1)
        self.senior_open.set(1)
        self.prestige_open.set(1)
        self.arpa_sequence.set(1) 

    def draw(self, name="", open_value=IntVar()):
        root = self.root
        content_frame = Frame(root)  
        content_frame.pack(fill=NONE, anchor='w')
        checkbox_normal = Checkbutton(content_frame, text=name, variable=open_value)  
        checkbox_normal.pack(side=LEFT)
        return content_frame
    
    def draw_int_text(self, name="", open_value=IntVar(), value=IntVar()):
        content_frame = self.draw(name+":", open_value)  
        vcmd = (self.root.register(self.validate_number), '%P')
        entry_normal = Entry(content_frame, width=20, textvariable=value, validate="key", validatecommand=vcmd) 
        entry_normal.pack(side=LEFT, expand=True) 

    def draw_combobox(self, name="", open_value=IntVar(), value=StringVar(), values=[]):
        value.set(values[0])
        content_frame = self.draw(name+":", open_value)
        combobox = ttk.Combobox(content_frame, values=values, textvariable=value, width=20, state="readonly")
        combobox.pack(side=LEFT) 
    
    def read_json_file(self, file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            strings = json.load(f)
        return strings
    
    def validate_number(self,P):  
        if P == "":  
            return True  
        try:  
            int(P)  
            return True  
        except ValueError:   
            return False  
  
    def on_validate(self, P, vcmd):  
        a = vcmd()
        print(a)
        if not a:  
            P.delete(0, END)  
            P.insert(0, vcmd.widget.get())  
    
    def run(self):
        self.root.mainloop()



